package com.ceres.system.service.impl;

import com.ceres.system.dao.AdminMapper;
import com.ceres.system.pojo.Admin;
import com.ceres.system.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 工具方法，根据传入的用户id和角色id数组添加关联表
     * @param roleIds
     * @param adminId
     */
    public void addAdminAndRole(Integer[] roleIds, Integer adminId) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                adminMapper.addAdminAndRole(roleId, adminId);
            }
        }

    }


    /**
     * 添加后台用户
     *
     * @param roleIds
     * @param admin
     */
    @Override
    public void addAdmin(Integer[] roleIds, Admin admin) {
        if (usernameExistChecking(admin)){
            //进行密码加密加盐处理,默认是没有处理的
            String gensalt = BCrypt.gensalt();
            admin.setPassword("123456");
            String saltPassword = BCrypt.hashpw(admin.getPassword(), gensalt);
            admin.setPassword(saltPassword);
            adminMapper.insertSelective(admin);
            Integer adminId = admin.getId();
            this.addAdminAndRole(roleIds, adminId);
        }else {
            throw new RuntimeException("用户名已存在");
        }
    }

    @Override
    public List<Admin> findAll() {
        List<Admin> adminList = adminMapper.selectAll();
        return adminList;
    }

    /**
     * 删除方法，将用户状态改为已删除
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //通过用户id获取admin对象
        Admin admin = adminMapper.selectByPrimaryKey(id);
        //将用户状态改为已删除
        admin.setStatus("2");
        //将修改后的用户状态信息更新
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public Admin findById(Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        admin.setPassword(null);
        return admin;
    }

    /**
     * 根据用户id查询关联角色
     *
     * @param id
     * @return
     */
    @Override
    public Integer[] findRoleByAdmin(Integer id) {
        Integer[] roleByAdmin = adminMapper.findRoleByAdmin(id);
        return roleByAdmin;
    }

    /**
     * 修改用户信息，并重新关联角色
     * @param roleIds
     * @param admin
     */
    @Override
    public void updateAdmin(Integer[] roleIds,Admin admin) {
        //根据用户修改后的信息，查询出数据库中的用户信息
        Admin admin1 = adminMapper.selectOne(admin);
        if (admin!=null){
            //将用户修改的字段更新到数据库中，id，username，status三个字段不可更改。
            admin1.setName(admin.getName());
            admin1.setPassword(admin.getPassword());
            admin1.setEmail(admin.getEmail());
            admin1.setPhone(admin.getPhone());
            adminMapper.updateByPrimaryKeySelective(admin1);
            //根据用户id删除关联的角色
            adminMapper.deleteRolesByAdminId(admin.getId());
            //根据用户id将新的角色信息添加到中间表中
            addAdminAndRole(roleIds,admin1.getId());
        }else {
            throw new RuntimeException("用户不存在");
        }

    }

    /**
     * 重置用户密码
     * @param id
     */
    @Override
    public void resetPassword(Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        if (!"2".equals(admin.getStatus())) {
            String gensalt = BCrypt.gensalt();
            admin.setPassword("123456");
            String saltPassword = BCrypt.hashpw(admin.getPassword(), gensalt);
            admin.setPassword(saltPassword);
            admin.setStatus("1");
            adminMapper.updateByPrimaryKeySelective(admin);
        }else {
            throw new RuntimeException("用户状态错误");
        }
    }

    /**
     * 多条件查询并分页
     * @param queryCondition 查询条件
     * @param page 当前页码
     * @param size 每页显示条数
     * @return
     */
    @Override
    public Page<Admin> queryAdmin(Map<String, Object> queryCondition, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryCondition!=null){
            //用户真实姓名
            if (queryCondition.get("name")!=null&&!"".equals(queryCondition.get("name"))){
                criteria.andLike("name","%"+queryCondition.get("name")+"%");
            }
            //用户登录名
            if (queryCondition.get("username")!=null&&!"".equals(queryCondition.get("username"))){
                criteria.andLike("username","%"+queryCondition.get("username")+"%");
            }
            //用户手机号
            if (queryCondition.get("phone")!=null&&!"".equals(queryCondition.get("phone"))){
                criteria.andLike("phone","%"+queryCondition.get("phone")+"%");
            }
        }
        return (Page<Admin>) adminMapper.selectByExample(example);
    }

    /**
     * 修改密码
     * @param password
     * @param userName
     */
    @Override
    public void changPassword(String password,String userName) {
        Admin adminByUsername = adminMapper.findAdminByUsername(userName);
        //进行密码加密加盐处理,默认是没有处理的
        String gensalt = BCrypt.gensalt();
        adminByUsername.setPassword(password);
        String saltPassword = BCrypt.hashpw(adminByUsername.getPassword(), gensalt);
        adminByUsername.setPassword(saltPassword);
        adminMapper.updateByPrimaryKeySelective(adminByUsername);
    }

    /**
     * 查询用户名是否存在
     * @param admin
     * @return
     */
    Boolean usernameExistChecking(Admin admin){
        String username = admin.getUsername();
        Admin admin1 = adminMapper.findAdminByUsername(username);
/*        if (admin1==null){
            return true;
        }else {
            return false;
        }*/
        return admin1==null?true:false;
    }
}
